import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import router from '../router'

// 用于存储正在进行的请求数量
let requestCount = 0
// loading实例
let loadingInstance = null

// 显示loading
const showLoading = () => {
  if (requestCount === 0) {
    loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(255, 255, 255, 0.7)'
    })
  }
  requestCount++
}

// 隐藏loading
const hideLoading = () => {
  requestCount--
  if (requestCount === 0 && loadingInstance) {
    loadingInstance.close()
    loadingInstance = null
  }
}

// 创建axios实例
const service = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 15000
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    showLoading()
    
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      // 设置统一的请求头
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    hideLoading()
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    hideLoading()
    
    const res = response.data
    
    // 根据后端的状态码进行处理
    if (res.code === 200) {
      return res.data
    } else {
      // 显示错误信息
      ElMessage.error(res.message || '请求失败')
      
      // 401: 未登录或token过期
      if (res.code === 401) {
        // 清除本地存储的登录信息
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        // 跳转到登录页
        router.push({
          path: '/login',
          query: {
            redirect: router.currentRoute.value.fullPath
          }
        })
      }
      return Promise.reject(new Error(res.message || '请求失败'))
    }
  },
  error => {
    hideLoading()
    
    console.error('响应错误:', error)
    // 处理 HTTP 错误状态码
    const status = error.response?.status
    switch (status) {
      case 401:
        ElMessage.error('未登录或登录已过期')
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        router.push('/login')
        break
      case 403:
        ElMessage.error('没有权限')
        break
      case 404:
        ElMessage.error('请求的资源不存在')
        break
      case 500:
        ElMessage.error('服务器错误')
        break
      default:
        ElMessage.error(error.message || '网络错误')
    }
    return Promise.reject(error)
  }
)

export default service 